/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { wsApi } from '@app-cad/server';
import i18n from 'i18next';
import { useState } from 'react';
import { BaseCommand } from '@amcax/base';
import { PickableCommandForm } from '@app-base/common/components/command-form/pickable';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { PickInputRJSFFormat } from '@app-base/common/components/command-form/constants';
import { useCommand } from '@app-base/common/hooks/useCommand';
interface CompoundDialogProps {
  title: string;
  onClose: () => void;
}
function CompoundDialog({ title, onClose }: CompoundDialogProps) {
  const [formData, setFormData] = useState({ models: [] });
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      models: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        uniqueItems: true,
        format: PickInputRJSFFormat.MultiPickModel,
      },
    },
  };
  useCommand('cmdCompound', {
    onClose,
  });
  const uiSchema: UiSchema = {
    models: {
      'ui:placeholder': '请选择需要合并的体',
      'ui:autofocus': true,
    },
  };
  const handleSubmit = async () => {
    const idArray = formData.models.map((item) => {
      return item.objInfo.dxid;
    });
    await wsApi.createCompound(idArray);
    onClose();
  };
  const isFormDataValid = () => {
    return formData.models.length > 0;
  };
  return (
    <PickableCommandForm
      schema={schema}
      title={title}
      extraUiSchema={uiSchema}
      formData={formData}
      onClose={onClose}
      onChange={(data) => {
        setFormData(data);
      }}
      onSubmit={handleSubmit}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCompound: BaseCommand = {
  id: 'CmdCompound',
  label: 'command.compound',
  icon: 'commands/elec/elec-compound',
  create: (label: string, onClose: () => void) => (
    <CompoundDialog
      title={i18n.t(label)}
      onClose={onClose}
    />
  ),
};
